package org.sidney3172.gwt.widgets.client.selector;

import java.util.Collection;
import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;

/**
 * Class is a simple textbox with ol on a bottom. This widget can be used for example for tag selection.
 * @author sidney3172
 *
 */
public class SelectorWidget extends SimplePanel implements KeyPressHandler{

	interface WidgetTemplate extends SafeHtmlTemplates{
		
		@Template("<div id=\"{0}\"></div><ol class=\"{1}\" id=\"{2}\"></ol>")
		SafeHtml getTemplate(String boxID, String listStyle, String listID);
	}
	
	SelectorResources resources;
	private TextBox box;
	private HashMap<String, String> itemList;
	private EventListener listener;
	private String boxID;
	private String listID;
	private boolean allowDuplicate = false;
	
	
	public SelectorWidget() {
		resources = GWT.create(SelectorResources.class);
		resources.style().ensureInjected();
		
		listID = DOM.createUniqueId();
		boxID = DOM.createUniqueId();
		
		WidgetTemplate template = GWT.create(WidgetTemplate.class);
		
		HTMLPanel panel = new HTMLPanel(template.getTemplate(boxID, resources.style().selector(), listID));
		setWidget(panel);
		
		box = new TextBox();
		box.setWidth("500px");
		box.addKeyPressHandler(this);
		panel.add(box, boxID);
		listener = new EventListener() {
			
			@Override
			public void onBrowserEvent(Event event) {
				Element el = event.getCurrentEventTarget().cast();
				itemList.remove(el.getId());
				el.getParentElement().removeFromParent();
			}
		};
		itemList = new HashMap<String, String>();
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if(event.getCharCode() == ',' || event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
			
			addItem(box.getValue());
			Scheduler.get().scheduleDeferred(new ScheduledCommand() {
				
				@Override
				public void execute() {
					box.setValue("");
				}
			});
			
		}
	}

	public void addItem(String text){
		if(text == null || text.trim().isEmpty())
			return;
		if(itemList.containsValue(text) && !allowDuplicate){
			return;
		}
		if(text.indexOf(',')!=-1){
			String first = text.substring(0,text.indexOf(','));
			String sec  =text.substring(text.indexOf(',')+1);
			addItem(first);
			addItem(sec);
			return;
		}
		Element li = DOM.createElement("li");
		li.setClassName(resources.style().item());
		li.setInnerText(text);
		
		String id = DOM.createUniqueId();
		Element close = DOM.createAnchor();
		close.setId(id);
		itemList.put(id, text);
		
		close.setClassName(resources.style().button());
		li.appendChild(close);
		Document.get().getElementById(listID).appendChild(li);
		
		Event.sinkEvents(close, Event.ONCLICK);
		Event.setEventListener(close, listener);
	}
	
	public Collection<String> getKeyWords(){
		return itemList.values();
	}
	
	public void clear(){
		itemList.clear();
		com.google.gwt.dom.client.Element el = Document.get().getElementById(listID).getFirstChildElement(); 
		while(el!=null){
			el.removeFromParent();
			el = Document.get().getElementById(listID).getFirstChildElement();
		}
		box.setValue("");
	}
	
}
